/*
package com.changzhi.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changzhi.common.util.Result;
import com.changzhi.common.util.TokenUtil;
import com.changzhi.ldyl.model.vo.CarnivalBeastVo;
import com.changzhi.ldyl.model.vo.NewLotteryVo;
import com.changzhi.service.CarnivalService;
import com.changzhi.service.impl.CarnivalServiceImpl;
import com.google.common.util.concurrent.RateLimiter;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint(path = "/ws/v2/{token}", port = "${ws.port}")
public class WebSocketServer {

    private static Map<String, Session> userToSessionMap = new ConcurrentHashMap<>();
    private static Map<String, String> sessionToUserMap = new ConcurrentHashMap<>();
    public final static Map<String, RateLimiter> userLimitMap = new ConcurrentHashMap<>();

    @Autowired
    private CarnivalService carnivalService;

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
        String token = (String)pathMap.get("token");
        log.info("onOpen,有新连接加入={}", token);
       String sessionId = session.id().toString();
        String userId = TokenUtil.getUidByToken(token);
        userToSessionMap.put(userId, session);
        sessionToUserMap.put(sessionId, userId);
        //返回初始化数据
        CarnivalBeastVo beastVo = carnivalService.getInitBeastInfo(userId);
        List<CarnivalBeastVo> list = carnivalService.realTimeRankings();
        beastVo.setRealTimeList(list);
        session.sendText(JSON.toJSONString(Result.success(beastVo)));
        log.warn("onOpen,有新连接加入={}，当前大小={}", userId, userToSessionMap.size());
        log.info("==========返回:userId={},data={}", userId, JSON.toJSONString(Result.success(beastVo)));
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("methodName:onMessage,message={}", message);
        String sessionId = session.id().toString();
        JSONObject jsonObject = JSON.parseObject(message);
        Integer type = jsonObject.getInteger("type");
        if(type == null){
            session.sendText(JSON.toJSONString(Result.error("类型不能为空")));
        }
        String userId = sessionToUserMap.get(sessionId);
        //限流
        RateLimiter rateLimiter = userLimitMap.get(userId);
        if(rateLimiter == null){
            rateLimiter = RateLimiter.create(5);
            userLimitMap.put(userId, rateLimiter);
        }
        boolean b = rateLimiter.tryAcquire();
        if(!b){
            //session .sendText(JSON.toJSONString(Result.error("请稍候重试")));
            return;
        }
        //
        if(userId == null){
            session.sendText(JSON.toJSONString(Result.error("session有误")));
        }
       if(type == 1){
            //打击年兽
            Integer harm = jsonObject.getInteger("harm");
            if(harm == null){
                session.sendText(JSON.toJSONString(Result.error("伤害不能为空")));
            }
            fightBeast(session, userId, harm);
        } else if(type == 2){
            CarnivalBeastVo beastVo = carnivalService.beastInfo(userId);
            session.sendText(JSON.toJSONString(Result.success(beastVo)));
        }
    }

    //发送消息（所有用户）
    public void fightBeast(Session session, String userId, Integer harm){
        if(CarnivalServiceImpl.ID == null){
            session.sendText(JSON.toJSONString(Result.error("年兽作战未开始~")));
        }
        Result result = carnivalService.attackBeast(userId, harm);
        session.sendText(JSONObject.toJSONString(result));
        if(result.getCode() != 0){
            return;
        }
        CarnivalBeastVo beastVo = (CarnivalBeastVo) result.get("data");
        beastVo.setGiftList(new ArrayList<>());
        beastVo.setLastHarmPrize(null);
        beastVo.setMaxHarmPrize(null);
        Set<Map.Entry<String, Session>> entries = userToSessionMap.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            beastVo.setMaxHarmPrize(null);
            String key = entry.getKey();
            if(userId.equals(key)){
                continue;
            } else if(StringUtils.isNotBlank(CarnivalServiceImpl.maxHarmUserId) && key.equals(CarnivalServiceImpl.maxHarmUserId)){
                List<NewLotteryVo> maxPrizeList = carnivalService.getPrizeList(CarnivalServiceImpl.ACTIVITY_ID_2, 2);
                beastVo.setMaxHarmPrize(maxPrizeList.get(0));
            }
            Session targetSession = entry.getValue();
            AtomicInteger targetHarm = CarnivalServiceImpl.HARM_MAP.get(key);
            beastVo.setTotalHarm(targetHarm == null ? 0 : targetHarm.intValue());
            targetSession.sendText(JSON.toJSONString(Result.success(beastVo)));
        }
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        String sessionId = session.id().toString();
        String userId = sessionToUserMap.get(session.id().toString());
        userToSessionMap.remove(userId);
        sessionToUserMap.remove(sessionId);
        log.info("onClose,userId={}", userId);
    }



    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("onError,error={}", throwable.getMessage());
        throwable.printStackTrace();
    }

    //当有新的连接进入时，对该方法进行回调 (权限认证)
    @BeforeHandshake
    public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
        session.setSubprotocols("stomp");
       */
/* if (!req.equals("ok")){
            System.out.println("Authentication failed!");
            session.close();
        }*//*

    }


    @OnBinary
    public void onBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    System.out.println("read idle");
                    break;
                case WRITER_IDLE:
                    System.out.println("write idle");
                    break;
                case ALL_IDLE:
                    System.out.println("all idle");
                    break;
                default:
                    break;
            }
        }
    }

}*/
